package top.yuzt.noticeserver.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.ParameterResolutionDelegate;
import org.springframework.web.bind.annotation.*;

import top.yuzt.noticeserver.entity.Groupmembers;
import top.yuzt.noticeserver.entity.Usergroups;
import top.yuzt.noticeserver.entity.Users;
import top.yuzt.noticeserver.mapper.UsergroupsMapper;
import top.yuzt.noticeserver.service.impl.GroupmembersServiceImpl;
import top.yuzt.noticeserver.service.impl.UsergroupsServiceImpl;

import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yuzt
 * @since 2024-05-03
 */
@RestController
@RequestMapping("/usergroups")
public class UsergroupsController {

    @Autowired
    private UsergroupsServiceImpl usergroupsService;

    @Autowired
    private GroupmembersServiceImpl groupmembersService;
    @Autowired
    private UsergroupsMapper usergroupsMapper;




    @GetMapping("/find")
    public Usergroups find(Integer id){
        return usergroupsMapper.findGroupsByGroupID(id);

    }
    @PostMapping("/save")
    public Boolean register(@RequestBody Usergroups usergroups){
        Integer uuid = generateUniqueGroupId();
        String pic = "http://localhost:8080/Local_files/def_groupicon.png";
        if (usergroups.getGroupicon() == "" ){
            usergroups.setGroupicon(pic);
        }
        if (usergroups.getGroupid() == null){
            if(usergroupsMapper.findGroupsByGroupID(uuid) == null){
                do {
                    uuid = generateUniqueGroupId(); // 生成新的ID的方法，可以根据你的需求来实现
                } while (usergroupsService.getById(uuid) != null); // 检查数据库中是否存在相同的ID，如果存在则继续生成新的ID直到找到一个唯一的ID为止
            }
            usergroups.setGroupid(uuid);
            Groupmembers groupmembers = new Groupmembers(uuid,usergroups.getOwnerid(),2);

            groupmembersService.save(groupmembers);
        }
        return usergroupsService.saveOrUpdate(usergroups);
    }
    private Integer generateUniqueGroupId() {
        UUID uuid = UUID.randomUUID();
        return Math.abs(uuid.hashCode()); // 使用UUID的hashCode()方法生成一个哈希码，然后取绝对值确保为正数
    }



}
